package ClientCommands;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.naming.*;

import org.json.simple.JSONObject;

import Annotations.IsClientCommand;
import Commands.CommandBase;
import Commands.ClientCommandBase;
import Helpers.ApplicationLogger;

@IsClientCommand
public class InitialiseClientCommands extends ClientCommandBase<Map<String, CommandBase>> {
	
	public InitialiseClientCommands()
	{
		setCommandName("InitialiseClientCommands");
		setCommandDescription("Command Initializer");
	}
	
	protected void ExecuteInternal()
    {
		Context ctx = null;
		try {
			ctx = new InitialContext();
		} catch (NamingException e) {
			ApplicationLogger.getInstance().LOG.error(e.getMessage());
		}
		
		Collection<String> commandList = new ArrayList<String>();
		try {
			commandList = (Collection<String>)ctx.lookup("CommandList");
		} catch (NamingException e) {
			ApplicationLogger.getInstance().LOG.error(e.getMessage());
		}
		
        Map<String, CommandBase> commandPrototypeCash = new HashMap<String, CommandBase>();
        	
        for (String commandName : commandList) {
        	
        	CommandBase currentCommand = null;
			try {
				ApplicationLogger.getInstance().LOG.info("Trying lookup command with name: " + commandName);
				currentCommand = (CommandBase) ctx.lookup(commandName);
			} catch (NamingException e) {
				ApplicationLogger.getInstance().LOG.error(e.getMessage());
			} 
        	boolean isClientCommand = GetIsClientStatusOfCommand(currentCommand);
        	
        	if(isClientCommand)
			{
				commandPrototypeCash.put(commandName, currentCommand);
			}
		}   

        setResult(commandPrototypeCash);
    }

	public boolean GetIsClientStatusOfCommand(CommandBase command)
	{
		IsClientCommand isclientAnntoation = command.getClass().getAnnotation(IsClientCommand.class);
		boolean commandIsClient = isclientAnntoation != null;
		ApplicationLogger.getInstance().LOG.info("current status of command " + command.getClass().getName() + 
				"isClientCommand annotation is not null: " + commandIsClient);
		return commandIsClient;
	}
	
	
	public void FillFromJSON(JSONObject jobj) {
		super.FillFromJSON(jobj);
	}
	
	public String toJSONString()
	{
		return super.toJSONString();
	}
}
